﻿
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using WorkFlow.Data.Model;
using RuleEntity = WorkFlow.Data.Model.RuleEntity;

namespace WorkFlow.Data
{
    public class DataManager
    {
        public SqlHelper _SqlHelper = new SqlHelper();
        public DataManager(SqlHelper sqlHelper)
        {
            _SqlHelper = sqlHelper;
        }
        public List<WorkFlowInfo> GetWorkFlowInfo(string workflowName, string user, int status, string message, string startTime, string endTime)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from workflowinfo where ";
            if (!string.IsNullOrEmpty(workflowName))
            {
                sql += $" WorkflowName like '%{workflowName}%' and ";
            }
            if (!string.IsNullOrEmpty(user))
            {
                sql += $" User like '%{user}%' and ";
            }
            if (status != -1)
            {
                sql += $" Status = '{status}' and ";
            }
            if (!string.IsNullOrEmpty(message))
            {
                sql += $" Message like '%{message}%' and ";
            }

            sql += $" CreateTime between '{startTime}' and '{endTime}' and ParentID=''";

            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<WorkFlowInfo> result = CommentTool.DataTableToEntityArray<WorkFlowInfo>(dataTable);
            return result;
        }

        public WorkFlowInfo GetWorkFlowInfoByID(string id)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from workflowinfo where ID='{id}'";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<WorkFlowInfo> result = CommentTool.DataTableToEntityArray<WorkFlowInfo>(dataTable);
            if (result.Count > 0)
            {
                return result[0];
            }
            return null;
        }

        public WorkFlowInfo GetWorkFlowInfoByDetailID(string detailID)
        {
            WorkFlowDetail workFlowDetail = GetWorkFlowDetailByID(detailID);
            WorkFlowInfo workFlowInfo = GetWorkFlowInfoByID(workFlowDetail.MainID);
            return workFlowInfo;
        }

        public List<WorkFlowDetail> GetAllWorkFlowDetailView()
        {
            DataTable dataTable = new DataTable();
            string sql = $"select a.*,b.WorkFlowName from workflowdetail a left join workflowinfo b on a.MainID=b.ID where a.Type=2 and a.Status=0";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<WorkFlowDetail> result = CommentTool.DataTableToEntityArray<WorkFlowDetail>(dataTable);
            return result;
        }

        public WorkFlowDetail GetWorkFlowDetailByID(string detailID)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select a.*,b.WorkFlowName from workflowdetail a left join workflowinfo b on a.MainID=b.ID where a.ID='{detailID}'";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<WorkFlowDetail> result = CommentTool.DataTableToEntityArray<WorkFlowDetail>(dataTable);
            if (result.Count > 0)
            {
                return result[0];
            }
            return null;
        }

        public List<WorkFlowDetail> GetWorkFlowDetailByMainID(string mainID)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from workflowdetail where MainID='{mainID}'";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<WorkFlowDetail> result = CommentTool.DataTableToEntityArray<WorkFlowDetail>(dataTable);
            return result;
        }


        public List<ParameterEntity> GetGlobalParametersByMainID(string mainID)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from parameter where DetailID in (select t.ID from (select ID from workflowdetail where MainID='{mainID}' LIMIT 1) as t) ";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<ParameterEntity> result = CommentTool.DataTableToEntityArray<ParameterEntity>(dataTable);
            return result;
        }
        public List<ParameterEntity> GetAllParameterEntityByMainID(string mainID)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from parameter where DetailID in (select ID from workflowdetail where MainID='{mainID}')";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<ParameterEntity> result = CommentTool.DataTableToEntityArray<ParameterEntity>(dataTable);
            return result;
        }

        public List<RuleEntity> GetRule(int id)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from rule where ID='{id}'";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<RuleEntity> result = CommentTool.DataTableToEntityArray<RuleEntity>(dataTable);
            return result;
        }
        public List<RuleEntity> GetRule(string name)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from rule";
            if (!string.IsNullOrEmpty(name))
            {
                sql += $" where Name like '%{name}%' ";
            }
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<RuleEntity> result = CommentTool.DataTableToEntityArray<RuleEntity>(dataTable);
            return result;
        }
        public string AddRule(string name)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from rule where Name='{name}'";
            DataTable ruleDT = _SqlHelper.myDataSet(sql).Tables[0];
            if (ruleDT != null && ruleDT.Rows.Count > 0)
            {
                return $"Name:{name} has exsit!";
            }
            sql = $"insert into rule value('0','{name}','-1')";
            string message;
            string id;
            _SqlHelper.ExecuteNonQueryAndID(sql, out id, out message);
            if (string.IsNullOrEmpty(message))
            {
                return message;
            }
            return message;
        }


        public string EditRule(int id, string name)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from rule where Name='{name}'";
            DataTable ruleDT = _SqlHelper.myDataSet(sql).Tables[0];
            if (ruleDT != null && ruleDT.Rows.Count > 0
                && ruleDT.Rows[0]["ID"].ToString() != id.ToString())
            {
                return $"Name:{name} has exsit!";
            }
            sql = $"update rule set Name='{name}' where ID='{id}'";
            string message;
            _SqlHelper.ExecuteNonQuery(sql, out message);
            if (string.IsNullOrEmpty(message))
            {
                return message;
            }
            return message;
        }

        public void UpdateRule_DetailID(int ruleID, int detailID)
        {
            string sql = $"update rule set RuleDetailID={detailID} where ID={ruleID}";
            string message;
            _SqlHelper.ExecuteNonQuery(sql, out message);
        }
        public void DeleteRule(int id)
        {
            string sql = $"delete from rule where ID='{id}'";
            string message;
            _SqlHelper.ExecuteNonQuery(sql, out message);
        }
        public List<RuleDetailEntity> GetRuleDetails()
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from ruledetail";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<RuleDetailEntity> result = CommentTool.DataTableToEntityArray<RuleDetailEntity>(dataTable);
            return result;
        }
        public RuleDetailEntity GetRuleDetails(int id)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from ruledetail where ID={id}";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<RuleDetailEntity> result = CommentTool.DataTableToEntityArray<RuleDetailEntity>(dataTable);
            if (result.Count > 0)
            {
                return result[0];
            }
            return null;
        }

        public int InsertRuleDetailEntity(RuleDetailEntity ruleDetailEntity)
        {
            string sql = $"insert into ruledetail values('0',{ruleDetailEntity.ParentID},{ruleDetailEntity.Type},{ruleDetailEntity.ValueType},'{ruleDetailEntity.Name}','{ruleDetailEntity.Value}')";
            string message;
            string id;
            _SqlHelper.ExecuteNonQueryAndID(sql, out id, out message);
            if (string.IsNullOrEmpty(message))
            {
                return int.Parse(id);
            }
            return -1;
        }

        public bool UpdateRuleDetailEntity(RuleDetailEntity ruleDetailEntity)
        {
            string sql = $"update ruledetail set Type={ruleDetailEntity.Type},ValueType={ruleDetailEntity.ValueType}," +
                $"Name='{ruleDetailEntity.Name}',Value='{ruleDetailEntity.Value}' where ID={ruleDetailEntity.ID}";
            string message;
            _SqlHelper.ExecuteNonQuery(sql, out message);
            if (!string.IsNullOrEmpty(message))
            {
                return false;
            }
            return true;
        }

        public bool DeleteRuleDetailEntity(RuleDetailEntity ruleDetailEntity)
        {
            string sql = $"delete from ruledetail where ID={ruleDetailEntity.ID}";
            string message;
            _SqlHelper.ExecuteNonQuery(sql, out message);
            if (!string.IsNullOrEmpty(message))
            {
                return false;
            }
            return true;
        }

        public List<ScheduledTaskEntity> GetScheduledTasks(string name)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from scheduledtask where Status=1 and ";
            if (!string.IsNullOrEmpty(name))
            {
                sql += $" Name like '%{name}%'";
            }
            else
            {
                sql += " 1=1";
            }
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<ScheduledTaskEntity> result = CommentTool.DataTableToEntityArray<ScheduledTaskEntity>(dataTable);
            return result;
        }

        public void DeleteScheduledTasks(int id)
        {
            string sql = $"update scheduledtask set Status=0 where ID={id}";
            string message;
            _SqlHelper.ExecuteNonQuery(sql, out message);
        }

        public void InsertTaskEntity(ScheduledTaskEntity taskEntity)
        {
            string sql = $"insert into scheduledtask values('0','{taskEntity.PlatformID}','{taskEntity.CompanyID}','{taskEntity.WorkFlowName}','{taskEntity.Name}',{taskEntity.Type},{taskEntity.Year},{taskEntity.Month},{taskEntity.Day},{taskEntity.Hour},{taskEntity.Minute},{taskEntity.Second},'{taskEntity.CreateTime}',1)";
            string message;
            string id;
            _SqlHelper.ExecuteNonQueryAndID(sql, out id, out message);
        }

        public void UpdateTaskEntity(ScheduledTaskEntity taskEntity)
        {
            string sql = $"update scheduledtask scheduledtask set PlatformID='{taskEntity.PlatformID}',CompanyID='{taskEntity.CompanyID}',WorkFlowName='{taskEntity.WorkFlowName}',Name='{taskEntity.Name}',Type={taskEntity.Type},Year={taskEntity.Year},Month={taskEntity.Month},Day={taskEntity.Day},Hour={taskEntity.Hour},Minute={taskEntity.Minute},Second={taskEntity.Second},'{taskEntity.CreateTime}'";
            string message;
            _SqlHelper.ExecuteNonQuery(sql, out message);
        }
        public List<TaskDetailEntity> GetTaskDetails(int parentID)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from taskdetail where ParentID={parentID}";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<TaskDetailEntity> result = CommentTool.DataTableToEntityArray<TaskDetailEntity>(dataTable);
            return result;
        }

        public List<PlatformInfo> GetPlatformInfos()
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from platforminfo where Status=1";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<PlatformInfo> result = CommentTool.DataTableToEntityArray<PlatformInfo>(dataTable);
            return result;
        }

        public List<CompanyInfo> GetCompanyInfos(int platformID)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from companyinfo where PlatformID={platformID} and Status=1";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<CompanyInfo> result = CommentTool.DataTableToEntityArray<CompanyInfo>(dataTable);
            return result;
        }

        public string SaveCompanyInfos(List<CompanyInfo> companyInfos, int platformID)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from companyinfo where PlatformID={platformID} and Status=1";
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            //List<CompanyInfo> result = CommentTool.DataTableToEntityArray<CompanyInfo>(dataTable);
            for (int i = 0; i < companyInfos.Count; i++)
            {
                CompanyInfo companyInfo = companyInfos[i];
                if (companyInfo.Opration == OprationType.Update)
                {
                    DataRow[] dataRows = dataTable.Select($"ID='{companyInfo.ID}'");
                    //if (dataRows.Length > 0)
                    //{
                    dataRows[0]["Name"] = companyInfo.Name;
                    //}
                }
                else if (companyInfo.Opration == OprationType.Delete)
                {
                    DataRow[] dataRows = dataTable.Select($"ID='{companyInfo.ID}'");
                    //if (dataRows.Length > 0)
                    //{
                    dataRows[0].Delete();
                    //}
                }
                else
                {
                    DataRow dataRow = dataTable.NewRow();
                    dataRow["ID"] = companyInfo.ID;
                    dataRow["PlatformID"] = platformID;
                    dataRow["Name"] = companyInfo.Name;
                    dataRow["Status"] = 1;
                    dataTable.Rows.Add(dataRow);
                }
            }
            string message;
            int count = _SqlHelper.SaveDataTable(sql, dataTable, out message);
            return message;
        }

        public List<WorkFlowFileEntity> GetWorkFlowFileEntity(string name)
        {
            DataTable dataTable = new DataTable();
            string sql = $"select * from WorkFlowFile";
            if (!string.IsNullOrEmpty(name))
            {
                sql += $" where Name like '{name}'";
            }
            dataTable = _SqlHelper.myDataSet(sql).Tables[0];
            List<WorkFlowFileEntity> result = CommentTool.DataTableToEntityArray<WorkFlowFileEntity>(dataTable);
            return result;
        }
        public string UpdateWorkFlowFileEntityName(int id, string name)
        {
            string sql = $"update WorkFlowFile set Name='{name}' where ID={id}";
            string message;
            _SqlHelper.ExecuteNonQuery(sql, out message);
            return message;
        }

        public void DeleteWorkFlowFileEntity(int id)
        {
            string sql = $"delete from WorkFlowFile where ID={id}";
            string message;
            _SqlHelper.ExecuteNonQuery(sql, out message);
        }


        public void InsertTaskDetailEntity(TaskDetailEntity taskDetailEntity)
        {
            string sql = $"insert into taskdetail values('0',{taskDetailEntity.ParentID},{taskDetailEntity.Result},'{taskDetailEntity.CreateTime}')";
            string message;
            string id;
            _SqlHelper.ExecuteNonQueryAndID(sql, out id, out message);
        }

        public int InsertWorkFlowFileEntity(WorkFlowFileEntity workFlowFileEntity)
        {
            string sql = $"insert into WorkFlowFile values('0',{workFlowFileEntity.GroupID},'{workFlowFileEntity.Name}','{workFlowFileEntity.FileName}')";
            string message;
            string id;
            _SqlHelper.ExecuteNonQueryAndID(sql, out id, out message);
            if (string.IsNullOrEmpty(message))
            {
                return int.Parse(id);
            }
            return -1;
        }
        //private List<T> GetDT<T>(DataTable dt)
        //{
        //    try
        //    {
        //        var res = JsonConvert.SerializeObject(dt);
        //        var mt = JsonConvert.DeserializeObject<List<T>>(res);
        //        if (mt.Count > 0)
        //            return mt;
        //        return default(List<T>);
        //    }
        //    catch (Exception e)
        //    {
        //        e = e.GetBaseException();
        //        LogHelper.WriteLog("GetDT", e);
        //        return default(List<T>);
        //    }
        //}


    }
}
